package com.eeepay.eeepay_v2.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 描述：截屏工具类
 * 作者：zhuangzeqin
 * 时间: 2017/7/19-10:24
 * 邮箱：zzq@eeepay.cn
 */
public class ScreenShot {
    // 获取指定Activity的截屏，保存到png文件
    public static Bitmap takeScreenShot(Activity activity,View view) {
        // View是你需要截图的View
//        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
        // 获取状态栏高度
//        Rect frame = new Rect();
//        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//        int statusBarHeight = frame.top;
//        Log.i("TAG", "" + statusBarHeight);
//        // 获取屏幕长和高
//        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
//        int height = activity.getWindowManager().getDefaultDisplay()
//                .getHeight();
        // 去掉状态栏，如果需要的话
        // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
//        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
//                - statusBarHeight);
        Bitmap b = Bitmap.createBitmap(b1, 0, 0, view.getWidth(), view.getHeight());
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(false);
        return b;
    }

    // 保存到sdcard
    private static void savePic(Activity activity, Bitmap b, File file, final ResultCallBack resultCallBack) {
        BufferedOutputStream fos = null;
        try {
            fos = new BufferedOutputStream(new FileOutputStream(file));
//          fos = new FileOutputStream(strFileName);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
            // 其次把文件插入到系统图库
            MediaStore.Images.Media.insertImage(activity.getContentResolver(), file.getAbsolutePath(), file.getName(), null);
            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            // 最后通知图库更新
//            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
            resultCallBack.onSuccess(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            resultCallBack.onFail("保存失败");
        } catch (IOException e) {
            e.printStackTrace();
            resultCallBack.onFail("保存失败");
        } catch (Exception ex) {
            ex.printStackTrace();
            resultCallBack.onFail("保存失败");
        }
    }

    // 程序入口，外界直接调用此方法即可
    public static void shoot(Activity activity,View screenshotView , final ResultCallBack resultCallBack) {
        // String path = getDiskCacheDir(activity.getApplicationContext()) + File.separator + System.currentTimeMillis() + ".png";
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "eeepay_images";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        ScreenShot.savePic(activity, ScreenShot.takeScreenShot(activity,screenshotView), file, resultCallBack);
    }

    /**
     * 获取缓存路径
     *
     * @param context
     * @return
     */
    private static String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    public interface ResultCallBack {
        void onSuccess(File file);//保存成功回调；图片的保存路径

        void onFail(String error);//保存失败；错误信息
    }

}
